package controllers

import dao.{AnnoDao, BasicDao}
import implicits.Implicits._
import models.Tables._
import play.api.cache.AsyncCacheApi
import play.api.libs.json.Json
import play.api.mvc._
import tool.FormTool
import tool.Pojo.KeywordInfo
import utils.Utils

import javax.inject.Inject
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future


/**
 * Created by yz on 16/9/2021
 */
class AnnoController @Inject()(cc: ControllerComponents, cache: AsyncCacheApi)(
  implicit val basicDao: BasicDao,
  implicit val annoDao: AnnoDao,
) extends AbstractController(cc) {

  def getAnnoByServer = Action.async { implicit request =>
    val map = request.body.asJson.get.toJsObject.value
    val pageData = FormTool.pageForm.bindFromRequest().get
    annoDao.selectAll(map, pageData).map { case (size, x) =>
      val array = Utils.getJsonByTs(x)
      Ok(Json.obj("rows" -> array, "total" -> size))
    }
  }

  def getSelect2Values = Action.async { implicit request =>
    val data = FormTool.keysForm.bindFromRequest().get
    annoDao.selectUniqueValues(data.keys).map { valuess =>
      val vMap = data.keys.zip(valuess).toSeqMap
      Ok(Json.toJson(vMap))
    }
  }

  def getAnnoById = Action.async { implicit request =>
    val data = FormTool.geneIdForm.bindFromRequest().get
    annoDao.selectByGeneId(data.geneId).map { x =>
      val array = Utils.getMapByT(x)
      Ok(Json.toJson(array))
    }
  }

  def getDetailInfo = Action.async { implicit request =>
    val geneNameOp = FormTool.geneNameOpForm.bindFromRequest().get.geneName
    val idF = geneNameOp.map { geneName =>
      annoDao.select(geneName).map { x =>
        x.id
      }
    }.getOrElse {
      Future {
        FormTool.geneIdForm.bindFromRequest().get.geneId
      }
    }
    idF.flatMap { id =>
      annoDao.selectTByGeneId(id).map { x =>
        Ok(views.html.genome.detailInfo(x))
      }
    }
  }

  def allGeneNames = Action.async {
    annoDao.selectAllGeneNames.map { x =>
      Ok(Json.toJson(x))
    }
  }


}
